 // pages/publish/publish.js
const API = require('../../common/constant.js');
const util = require('../../utils/util');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isPublish: false,
    eventInfo:{},
    typePick: {
      array: ['#求邂逅#', '#美食搭伙#', '#解闷聊天#'],
      index: '',
      isTypePick: false,
    },
    numPick: {
      array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
      index: '',
      isNumPick: false
    },
    sexPick: {
      array: ['不限', '男', '女'],
      index: '',
      isSexPick: false
    },
    payPick: {
      array: ['我请客', 'AA制', '男A女免'],
      index: '',
      isPayPick: false
    },
    travelPick: {
      array: ['各自出行', '我接送（发起人接送）'],
      index: '',
      isTravelPick: false
    },
    eventAddress: "请选择",
    isEventData: false,
    isEventStartTime: false,
    isEventEndTime: false
  },
  typePickerChange: function (e) {
    this.setData({
      ['typePick.index']: e.detail.value,
      ['typePick.isTypePick']: true
    })
  },
  numPickerChange: function (e) {
    this.setData({
      ['numPick.index']: e.detail.value,
      ['numPick.isNumPick']: true
    })
  },
  sexPickerChange: function (e) {
    this.setData({
      ['sexPick.index']: e.detail.value,
      ['sexPick.isSexPick']: true
    })
  },
  payPickerChange: function (e) {
    this.setData({
      ['payPick.index']: e.detail.value,
      ['payPick.isPayPick']: true
    })
  },
  travelPickerChange: function (e) {
    this.setData({
      ['travelPick.index']: e.detail.value,
      ['travelPick.isTravelPick']: true
    })
  },
  bindDateChange: function (e) {
    this.setData({
      eventData: e.detail.value,
      isEventData: true
    })
  },
  bindTimeChange: function (e) {
    if(e.target.id === 'eventStartTime') {
      this.setData({
        eventStartTime: e.detail.value,
        isEventStartTime: true,
      })
    } else {
      this.setData({
        eventEndTime: e.detail.value,
        isEventEndTime: true,
      })
    }
  },
  getTitle: function(e) {
    this.setData({
      eventTitle : e.detail.value
    })
  },
  getEventContent: function (e) {
    this.setData({
      eventContent: e.detail.value
    })
  },
  compareTime(t1, t2){
    var date = new Date();
    var a = t1.split(":");
    var b = t2.split(":");
    return date.setHours(a[0], a[1]) < date.setHours(b[0], b[1]);
  },
  compareData(date1, date2){
    var oDate1 = new Date(date1);
    var oDate2 = new Date(date2);
    return oDate1.getTime() < oDate2.getTime()
  },
  MinutesTest(e){
    e = e.replace(/-/g, '/');
    let sdate1 = new Date(e);
    sdate1.setMinutes(sdate1.getMinutes() - 1);
    let timeOne = sdate1.getHours();
    let timeTwo = sdate1.getMinutes();
    if (timeOne < 10){
      timeOne = '0' + timeOne;
    }
    if (timeTwo < 10) {
      timeTwo = '0' + timeTwo;
    }
    let now = timeOne + ":" + timeTwo;  
    return now;  
  },
  // 得到发布活动的信息
  getPublishInfo: function (){
    if (this.data.isPublish) {
      console.log('正在发布');
      return;
    }
    let eventInfo = this.data.eventInfo;
    //标题
    if (this.data.eventTitle) {
      eventInfo.eventTitle = this.data.eventTitle;
      if (this.data.eventTitle.length>20){
        app.showUserInfo('活动标题不能超过20字', 'none', 1500);
        return
      }
    } else {
      app.showUserInfo('请填写标题', 'none', 1500);
      return
    }
    //类型
    if (this.data.typePick.index === "0") {
      eventInfo.eventType = "find"
    } else if (this.data.typePick.index === "1") {
      eventInfo.eventType = 'partner'
    } else if (this.data.typePick.index === "2") {
      eventInfo.eventType = 'chat'
    } else {
      app.showUserInfo('请填写活动类型', 'none', 1500);
      return
    }
    //时间
    if (!(this.data.eventData)) {
      app.showUserInfo('请填写活动日期', 'none', 1500);
      return
    }
    if (!(this.data.eventStartTime)) {
      app.showUserInfo('请填写开始时间', 'none', 1500);
      return
    }
    if (!(this.data.eventEndTime)) {
      app.showUserInfo('请填写结束时间', 'none', 1500);
      return
    }
    eventInfo.eventStartTime = this.data.eventData + " " + this.data.eventStartTime + ':00';
    eventInfo.eventEndTime = this.data.eventData + " " + this.data.eventEndTime + ':00';
    eventInfo.registrationEndTime = this.data.eventData + " " + this.MinutesTest(eventInfo.eventStartTime) + ':59';
    
    if (this.data.eventStartTime === this.data.eventEndTime) {
      app.showUserInfo("时间不能一样", 'none', 1500);
      return;
    }
    if (!this.compareTime(this.data.eventStartTime, this.data.eventEndTime)) {
      app.showUserInfo("必须是未来时间", 'none', 1500);
      return;
    }
    //介绍
    if (this.data.eventContent) {
      eventInfo.eventContent = this.data.eventContent;
    } else {
      app.showUserInfo('请填写介绍', 'none', 1500);
      return
    }

    //人数
    if (this.data.numPick.array[this.data.numPick.index]) {
      eventInfo.eventNumber = this.data.numPick.array[this.data.numPick.index];
    } else {
      app.showUserInfo('请填写参与人数', 'none', 1500);
      return
    }

    //性别
    if (this.data.sexPick.index + ""){
      eventInfo.registrationSex = this.data.sexPick.index + "";
    } else {
      app.showUserInfo('请填写参与者性别', 'none', 1500);
      return
    }

    //付款方式
    if (this.data.payPick.index === "0") {
      eventInfo.payMethod = "me_treat"
    } else if (this.data.payPick.index === "1") {
      eventInfo.payMethod = 'aa'
    } else if (this.data.payPick.index === "2") {
      eventInfo.payMethod = 'male_a_female_free'
    }else{
      app.showUserInfo('请填写买单方式', 'none', 1500);
      return
    }

    //地址
    if (this.data.eventAddress != '请选择') {
      eventInfo.eventAddress = this.data.eventAddress;
    } else {
      app.showUserInfo('请填写地址', 'none', 1500);
      return
    }

    //出行方式
    if (this.data.travelPick.index === "0") {
      eventInfo.travelModel = 'self'
    } else if (this.data.travelPick.index === "1") {
      eventInfo.travelModel = 'me_transfer'
    }else{
      app.showUserInfo('请填写出行方式', 'none', 1500);
      return
    }
    eventInfo.longitude = this.data.longitude;
    eventInfo.latitude = this.data.latitude;
    eventInfo.cityCode = this.data.cityCode;
    this.setData({
      eventInfo: eventInfo
    })

    this.saveEventInfo(eventInfo);
  },

  // 发布活动
  saveEventInfo : function (params) {
    let that = this;
    if (this.data.isPublish) {
      console.log('正在发布');
      return;
    }
    this.setData({
      isPublish: true
    })
    let sessionId = wx.getStorageSync('sessionId');
    let openId = wx.getStorageSync('openId');
    wx.request({
      url: API.URL.EVENT.SAVE_EVENTINFO + `?sessionId=${sessionId}&openId=${openId}`,
      data: {
        ...params
      },
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      success: function(res){
        if(res.data.status === 200){
          app.globalData.isNewIndex = true;
          app.globalData.isNewNearBy = true;
          wx.showToast({
            title: '发布成功',
            duration: 1500
          })
          setTimeout(function () {
            wx.redirectTo({
              url: '../publish/pubSuccess?id=' + res.data.data.bussData
            });
          }, 1500)
        }else{
          that.setData({
            isPublish: false
          })
          console.log(res);
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1500
          })
        }
      },
      fail: function(res) {
        that.setData({
          isPublish: false
        })
        console.log('发布活动失败', res);
        app.showUserInfo(res.msg, 'none', 2000);
      }
    })
  },

  onLoad: function (options) {
    if (!app.globalData.hasUserInfo) {
      return;
    }
    //检测用户是否手机登录
    if (!app.isPhoneLogin()) {
      app.showUserInfo('您还没有登录，暂不能发布活动，2s后自动为您跳到登录页面', 'none', 1000)
      setTimeout(function () {
        wx.redirectTo({
          url: '../loginAndRegister/loginAndRegister'
        });
      }, 2000)
      return;
    }
    app.showUserInfo('用户报名时间为当前时间至活动开始时间', 'none', 2000);
  },
  onUnload: function(){
    this.setData({
      isPublish: false
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
    if (!app.globalData.hasUserInfo) {
      app.showUserInfo('请授权，2s后自动跳转首页', 'none', 2000);
      setTimeout(function () {
        wx.switchTab({
          url: '../index/index'
        })
      }, 2000)
      return;
    }
    let globalData = app.globalData;
    if (globalData.title){
      this.setData({
        eventAddress: globalData.title,
        longitude: globalData.longitude,
        latitude: globalData.latitude,
        cityCode: globalData.cityCode
      })
      app.globalData.title = '';
      app.globalData.longitude = '';
      app.globalData.latitude = '';
      app.globalData.cityCode = '';
    }
    else{
      this.setData({
        eventAddress: "请选择"
      })
    }

  }
})